package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.UnitForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@Service
public class UnitService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "queryFallback")
    public Result<List<Map<String, Object>>> query(String levelId) {
        return restTemplate.getForEntity("http://producer/unit/query?levelId={1}", Result.class, levelId).getBody();
    }

    @SentinelResource(fallback = "queryByLevelAndUserFallback")
    public Result<List<Map<String, Object>>> queryByLevelAndUser(String levelId, String userId) {
        return restTemplate.getForEntity("http://producer/unit/queryByLevelAndUser?levelId={1}&userId={2}", Result.class, levelId, userId).getBody();
    }

    public Result queryFallback(String levelId) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result queryByLevelAndUserFallback(String levelId, String userId) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result getFallback(String levelId) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "getFallback")
    public Result get(String id) {
        return restTemplate.getForEntity("http://producer/unit/{1}", Result.class, id).getBody();
    }

    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody UnitForm form) {
        return restTemplate.postForEntity("http://producer/unit", form, Result.class).getBody();
    }

    @SentinelResource(fallback = "updateFallback")
    public Result update(@RequestBody UnitForm form) {
        restTemplate.put("http://producer/unit/{1}",form,form.getId());
        return Result.success();
    }
    public Result saveFallback(@RequestBody UnitForm form) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result updateFallback(UnitForm level) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }
}
